import { useState, useCallback, useEffect } from 'react';
import { User } from './lxdy';
import { getInitialUser } from './gjhs';
import { names, colors } from './cldy';

export const useEditorState = (room: string, provider: any) => {

    useEffect(() => {
        if (provider) {
          // 随机选择一个名字和颜色
          const randomName = names[Math.floor(Math.random() * names.length)];
          const randomColor = colors[Math.floor(Math.random() * colors.length)];
    
          // 设置用户信息
          provider.awareness.setLocalStateField('user', {
            name: randomName,
            color: randomColor,
          });
        }
      }, [provider]);
      
    const [status, setStatus] = useState<'connecting' | 'connected' | 'disconnected'>('connecting');

    // 添加 provider 状态监听
    useEffect(() => {
        const handleStatus = (event: { status: 'connecting' | 'connected' | 'disconnected' }) => {
            setStatus(event.status);
        };

        // 立即检查当前状态
        if (provider.status) {
            setStatus(provider.status);
        }

        provider.on('status', handleStatus);

        return () => {
            provider.off('status', handleStatus);
        };
    }, [provider]);


    const [currentUser, setCurrentUser] = useState<User>(getInitialUser());
    const [projectId, setProjectId] = useState<number>(1001);
    const [isEditMode, setIsEditMode] = useState(() => {
        const stored = localStorage.getItem(`isEditMode_${room}`);
        return stored ? JSON.parse(stored) : false;
    });
    const [currentEditId, setCurrentEditId] = useState<number | null>(() => {
        const stored = localStorage.getItem(`currentEditId_${room}`);
        return stored ? JSON.parse(stored) : null;
    });

    // 状态同步
    useEffect(() => {
        localStorage.setItem(`isEditMode_${room}`, JSON.stringify(isEditMode));
    }, [isEditMode, room]);

    useEffect(() => {
        localStorage.setItem(`currentEditId_${room}`, JSON.stringify(currentEditId));
    }, [currentEditId, room]);

    return {
        status,
        setStatus,
        currentUser,
        setCurrentUser,
        projectId,
        setProjectId,
        isEditMode,
        setIsEditMode,
        currentEditId,
        setCurrentEditId,
    };
};